#include <Arduino.h>
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

const char *deviceName = "ESP32_Classic_BT";
bool isConnected = false;

void setup() {
    Serial.begin(115200);
    pinMode(2, OUTPUT);  // LED指示灯
    pinMode(14, INPUT_PULLDOWN);   // 新增：D14输入引脚
    
    if (!SerialBT.begin(deviceName)) {
        Serial.println("蓝牙初始化失败!");
        while(1);
    }
    
    Serial.println("蓝牙已启动，等待连接...");
    SerialBT.register_callback([](esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
        if (event == ESP_SPP_SRV_OPEN_EVT) {
            isConnected = true;
            digitalWrite(2, HIGH);  // 连接时LED常亮
            Serial.println("设备已连接");
        } else if (event == ESP_SPP_CLOSE_EVT) {
            isConnected = false;
            digitalWrite(2, LOW);
            Serial.println("设备已断开");
        }
    });
}

void loop() {
    // 检测D14高电平
    if(digitalRead(14)) {
        if(isConnected) {
            SerialBT.write(0x55);  // 发送固定值0x55
            Serial.println("检测到高电平，已发送数据: 0x55");
            
            // LED闪烁反馈
            digitalWrite(2, LOW);
            delay(100);
            digitalWrite(2, HIGH);
        }
        
        // 等待高电平结束（简单防抖）
        while(digitalRead(14)) delay(10);
    }
    
    delay(10);  // 降低CPU占用
}